import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('../views/index.vue'),
    redirect:'/home',
    children: [{
        path: '/order',
        name: 'order',
        component: () => import('../views/pages/order.vue')
      },
      {
        path: '/collect',
        name: 'collect',
        component: () => import('../views/pages/collect.vue')
      }, {
        path: '/shopcar',
        name: 'shopcar',
        component: () => import('../views/pages/shopcar.vue')
      },
      {
        path: '/home',
        name: 'home',
        component: () => import('../views/pages/home.vue')
      }, {
        path: '/allshop',
        name: 'allshop',
        component: () => import('../views/pages/allshop.vue')
      }, {
        path: '/person',
        name: 'person',
        component: () => import('../views/pages/person.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (localStorage.getItem('token')) {
    next()
  } else {
    if (to.path == '/home'||to.path == '/allshop'||to.path == '/person') {
      next()
    } else {
      next('/home')
    }
  }
})

//为了防止router中push方法的bug出现：
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  if (typeof (location) == "string") {
    var Separator = "&";
    if (location.indexOf('?') == -1) {
      Separator = '?';
    }
    location = location + Separator + "random=" + Math.random();
  }
  return routerPush.call(this, location).catch(error => error)
}
export default router